package controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import utils.CustomizeProgressBar;
import utils.Utils;
import utils.XmlParser;
import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
import app.cloudstringers.Home;
import app.cloudstringers.R;
import define.API;
import define.Constants;
import define.Key;

public class HomeAsync extends AsyncTask<String, Void, Boolean> {

	private static final String TAG = HomeAsync.class.getSimpleName();

	private float total_space_in_long = 0;
	private float used_space_in_long = 0;

	private String TOTAL_SPACE = null, USED_SPACE = null,
			AVAILABLE_SPACE = null;

	private static final String KEY_TAG = "USER_ID"; // parent node
	private static final String KEY_ALLOCATED = "ALLOCATED";
	private static final String KEY_USED = "USED";

	private CustomizeProgressBar mCpbPercentage;
	private TextView mTvCapacity, mTvLowStorage;

	private Activity activity;
	private Context context;
	private XmlParser mXMLParser;

	public HomeAsync(Context context) {
		this.activity = (Activity) context;
		this.context = context;

		Utils.initialConnectionDialog(context);
	}

	@Override
	protected Boolean doInBackground(String... params) {
		HttpClient mHttpClient = new DefaultHttpClient();
		HttpPost mhHttpPost = new HttpPost(API.CHECK_SPACE);

		List<NameValuePair> mListNameValue = new ArrayList<NameValuePair>(2);
		mListNameValue
				.add(new BasicNameValuePair(Key.KEY_GLOBAL_ID, params[0]));

		try {
			mhHttpPost.setEntity(new UrlEncodedFormEntity(mListNameValue));

			HttpResponse mHttpResponse = mHttpClient.execute(mhHttpPost);
			HttpEntity mHttpEntity = mHttpResponse.getEntity();

			String XML = EntityUtils.toString(mHttpEntity);

			// Log.i(TAG, XML);

			mXMLParser = new XmlParser();
			Document mDocument = mXMLParser.getDomElement(XML);

			NodeList mNodeList = mDocument.getElementsByTagName(KEY_TAG);
			for (int i = 0; i < mNodeList.getLength(); i++) {
				if (mNodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
					Element mElement = (Element) mNodeList.item(i);

					TOTAL_SPACE = mXMLParser.getValue(mElement, KEY_ALLOCATED);
					USED_SPACE = mXMLParser.getValue(mElement, KEY_USED);

					NumberFormat mNfTotalSpace = NumberFormat.getInstance();
					NumberFormat mNfUsedSpace = NumberFormat
							.getNumberInstance();

					mNfUsedSpace.setMinimumFractionDigits(2);
					mNfUsedSpace.setMaximumFractionDigits(2);

					Number mNumberTotalSpace = mNfTotalSpace.parse(TOTAL_SPACE);
					Number mNumberUsedSpace = mNfTotalSpace.parse(USED_SPACE);

					total_space_in_long = mNumberTotalSpace.longValue();
					used_space_in_long = mNumberUsedSpace.longValue();

					TOTAL_SPACE = mNfTotalSpace
							.format(total_space_in_long / 1000);
					AVAILABLE_SPACE = mNfTotalSpace
							.format((double) (total_space_in_long - used_space_in_long) / 1000);
				}
			}

			return true;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
			return false;
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
			return false;
		} catch (ConnectTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (SocketException e) {
			e.printStackTrace();
			return false;
		} catch (SocketTimeoutException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		// Show progress dialog
		// Constants.connectivity.showProgressDialog();

		// Define here
		mTvCapacity = (TextView) this.activity.findViewById(R.id.tv_capacity);
		mTvLowStorage = (TextView) this.activity
				.findViewById(R.id.tv_low_storage);
		mCpbPercentage = (CustomizeProgressBar) this.activity
				.findViewById(R.id.cpb_percentage);
	}

	@Override
	protected void onPostExecute(Boolean result) {
		if (!result) {
			Constants.utils.showConnectionTimeoutDialog(context,
					Home.class);
		} else {
			// Set data for capacity to show
			if (AVAILABLE_SPACE == null) {
				mTvCapacity.setText("Available: 0 MB" + " GB\n Capacity: "
						+ TOTAL_SPACE + " GB");
			} else {
				if (total_space_in_long - used_space_in_long > 1000) {
					mTvCapacity
							.setText("Available: "
									+ String.format("%.02f",
											Float.valueOf(AVAILABLE_SPACE))
									+ " GB\n Capacity: "
									+ String.format("%.02f",
											Float.valueOf(TOTAL_SPACE)) + " GB");
				} else {
					mTvCapacity
							.setText("Available: "
									+ String.format("%.02f",
											total_space_in_long
													- used_space_in_long)
									+ " MB\n Capacity: "
									+ String.format("%.02f",
											Float.valueOf(TOTAL_SPACE)) + " GB");
				}
				// Set progress for progress dialog
				if (total_space_in_long != 0) {
					mCpbPercentage
							.setProgress((int) (100 * used_space_in_long / total_space_in_long));
				}

				// If available is less than 20% total capacity
				// Show alert red text
				if ((total_space_in_long - used_space_in_long) < (total_space_in_long * 20) / 100) {
					mTvLowStorage.setText(context
							.getString(R.string.low_storage));
				}
			}
		}

		// Constants.connectivity.hideProgressDialog();
	}
}
